import { defineConfig } from 'vite'
import { visualizer } from 'rollup-plugin-visualizer'
import vue from '@vitejs/plugin-vue'
import legacy from '@vitejs/plugin-legacy'
import path from 'path'

// 获取当前项目名称
const getProjectName = () => {
  const projectPath = process.cwd()
  return projectPath.split('/').pop() // 获取路径最后一段作为项目名
}

export default defineConfig({
  plugins: [
    vue(),
    legacy({
      // 浏览器目标配置
      targets: [
        'defaults', // 默认浏览器支持
        'Chrome >= 75', // 明确支持 Chrome 75
      ],
      // polyfills: true,
      // 自动引入必要的 Polyfill
      /*  polyfills: [
        'es.promise', // 为 Promise 提供完整支持
        'es.array.flat', // Array.prototype.flat
        'es.object.assign', // Object.assign
        'es.symbol', // Symbol 支持
        'es.promise.finally', // Promise.prototype.finally
      ], */
    }),
  ],
  base: './',
  resolve: {
    alias: {
      '@root': path.resolve(__dirname, 'src'),
      '@': path.resolve(process.cwd(), 'src'),
    },
  },

  build: {
    terserOptions: {
      compress: {
        drop_console: false,
        drop_debugger: false,
      },
    },
    target: 'es2015',
    // 设置输出目录为根目录的 dist/项目名
    outDir: path.resolve(__dirname, `dist/${getProjectName()}`),
    emptyOutDir: true,
    minify: 'terser',
    cssCodeSplit: true,
    rollupOptions: {
      output: {
        chunkFileNames: 'assets/js/[name]-[hash].js',
        entryFileNames: 'assets/js/[name]-[hash].js',
        assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
        manualChunks: {
          'vue-vendor': ['vue', 'pinia'],
        },
      },
      plugins: [
        visualizer({
          // open: true,
          gzipSize: true,
          brotliSize: true,
          filename: 'stats.html',
        }),
      ],
    },
  },
})
